
<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}分类</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      style="margin-top: 30px"
      @submit.native.prevent
    >
      <el-form-item label="上级分类">
        <el-select v-model="ruleForm.parent" placeholder="请选择上级分类">
          <el-option
            v-for="item in parents"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: ["id"],
  data() {
    return {
      ruleForm: {
        name: "",
        parent: "",
      },
      parents: [],
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getParents();
    this.fetch();
  },
  methods: {
    fetch() {
      this.id &&
        this.$http.get("rest/categories/" + this.id).then((res) => {
          if (res.status === 200) {
            this.ruleForm = Object.assign({}, this.ruleForm, res.data);
          }
        });
    },
    getParents() {
      this.$http.get("rest/categories").then((res) => {
        if (res.status === 200) {
          this.parents = res.data;
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
            .post(
              "rest/categories" + (this.id ? `/${this.id}` : ""),
              this.id ? { id: this.id, ...this.ruleForm } : this.ruleForm
            )
            .then((res) => {
              if (res.status === 200) {
                this.$router.push("/categories/list");
                this.$message({
                  type: "success",
                  message: "保存成功",
                });
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>